/*
 * 地址选择
 */
'use strict';
import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    TouchableHighlight,
    TouchableOpacity,
    Image,
    PixelRatio,
    Dimensions,
    Platform,
    ScrollView,
    AsyncStorage,
    TextInput,
} from 'react-native';


import Toast from 'antd-mobile/lib/toast';
import List from 'antd-mobile/lib/list';
import InputItem from 'antd-mobile/lib/input-item';
import Picker from 'antd-mobile/lib/picker';
import TextareaItem from 'antd-mobile/lib/textarea-item';
import ActivityIndicator from 'antd-mobile/lib/activity-indicator';

import NavTitle from '../component/NavTitle';
var ImagePicker = require('react-native-image-picker');

import { createForm } from 'rc-form';

import XFetch from '../XFetch';
import MapSelect from './MapSelect';

const Item = List.Item;

let _lat,_lng;

class EditMyService extends Component {
    constructor(props) {
        super(props);

        this._timer = void 0;

        this.state = {
            files: [],
            logoFiles: [],
            sValue: [],
            logoImage:void 0,
            productImgs:[],
            detaiImgs:[],
            classifys:[],
            animating:false,
        }
    }

    componentDidMount(){
        this._getClassify();
    }

    _getInfo(){
        XFetch(`http://www.weiweigo.com/app/server.aspx?method=showDetail&serveid=${this.props.id}`,{
            method:'GET',
        }).then(data=>{
            _lat = data.lat;
            _lng = data.lon;
            this.setState({
                logoImage: {
                    uri:`http://www.weiweigo.com${data.imgUrl}`
                },
                productImgs:data.focusimg?JSON.parse(data.focusimg).map(ele=>{
                    return {
                        uri:`http://www.weiweigo.com${ele.src}`
                    }
                }):[],
                detaiImgs:data.content_img?JSON.parse(data.content_img).map(ele=>{
                    return {
                        uri:`http://www.weiweigo.com${ele.src}`
                    }
                }):[],
                animating:false
            },()=>{
                this.props.form.setFieldsValue({
                    Name:data.title,
                    ClassID:[data.classId],
                    addressDetail:data.addressDetail,
                    tel:data.tel,
                    summary:data.summary,
                    acontent:data.content
                })
            })
        });
    }


    _getClassify(){
        this.setState({
            animating:true
        });
        XFetch(`http://www.weiweigo.com/app/type.aspx?method=show&chnid=2&pid=189`,{
            method:'GET'
        }).then(data=>{
            this.setState({
                classifys:data.map(ele=>{
                    return {
                        label: ele.className,
                        value: ele.classId,
                    }
                })
            },()=>{
                if(this.props.id && this.props.id != 0){
                    this._getInfo();
                }else{
                    this.setState({
                        animating:false
                    });
                }
            })
        });
    }

    _uploadImg(img,obj,c) {
        let myHeaders = new Headers();
        myHeaders.append('Content-Type', 'multipart/form-data');

        let formData = new FormData();

        formData.append('imgFile', {uri: img.uri, name: img.fileName, type: 'image/jpeg'});
        formData.append('c', c);

        fetch(`http://www.weiweigo.com/app/member.aspx?method=upImg`,{
            method: 'POST',
            headers:myHeaders,
            body: formData,
        })
        .then(res => {
            res.json().then(data=>{
                if(data.success){
                    if(Object.prototype.toString.call(obj) === '[object Array]'){
                        obj.push(data.val)
                    }else{
                        obj.imgUrl=data.val;
                    }
                }else{
                    this.setState({
                        animating:false
                    });
                    clearInterval(this._timer);
                }
            });
        })
    }

    _selectImage(){
        let options = {
            title: '',
            cancelButtonTitle:'取消',
            takePhotoButtonTitle:'拍照',
            chooseFromLibraryButtonTitle:'相册选择',
            mediaType:'photo',
            quality: 0.5
        };
        ImagePicker.showImagePicker(options, (response) => {
            setTimeout(function(){
                this._uploadImg({uri:response.uri.replace('file://', ''),isStatic: true,fileName:response.fileName});
            }.bind(this),500);
        });
    }

    _selectLogo(){
        let options = {
            title: '',
            cancelButtonTitle:'取消',
            takePhotoButtonTitle:'拍照',
            chooseFromLibraryButtonTitle:'相册选择',
            mediaType:'photo',
            quality: 0.5
        };
        ImagePicker.showImagePicker(options, (response) => {
            let source = null;

            if(response.didCancel){
                return;
            }

            if(Platform.OS === 'ios') {
                // uri (on iOS)
                source = {uri: response.uri.replace('file://', ''), isStatic: true,fileName:response.fileName};
            } else {
                // uri (on android)
                source = {uri: response.uri, isStatic: true, fileName:response.fileName};
            }

            this.setState({
                logoImage:source
            })
        });
    }

    _selectProductImgs(){
        let options = {
            title: '',
            cancelButtonTitle:'取消',
            takePhotoButtonTitle:'拍照',
            chooseFromLibraryButtonTitle:'相册选择',
            mediaType:'photo',
            quality: 0.5
        };
        ImagePicker.showImagePicker(options, (response) => {
            let source = null;

            if(response.didCancel){
                return;
            }

            if(Platform.OS === 'ios') {
                // uri (on iOS)
                source = {uri: response.uri.replace('file://', ''), isStatic: true,fileName:response.fileName};
            } else {
                // uri (on android)
                source = {uri: response.uri, isStatic: true, fileName:response.fileName};
            }

            this.setState({
                productImgs: [source],
            })
        });
    }

    _selectDetailImgs(){
        let options = {
            title: '',
            cancelButtonTitle:'取消',
            takePhotoButtonTitle:'拍照',
            chooseFromLibraryButtonTitle:'相册选择',
            mediaType:'photo',
            quality: 0.5
        };
        ImagePicker.showImagePicker(options, (response) => {
            let source = null;

            if(response.didCancel){
                return;
            }

            if(Platform.OS === 'ios') {
                // uri (on iOS)
                source = {uri: response.uri.replace('file://', ''), isStatic: true,fileName:response.fileName};
            } else {
                // uri (on android)
                source = {uri: response.uri, isStatic: true, fileName:response.fileName};
            }

            this.setState({
                detaiImgs: [...this.state.detaiImgs, source],
            })
        });
    }

    _renderImgs(){
        return this.state.productImgs.map((ele, index) => {
            return(
                <TouchableOpacity
                    key = {index}
                    onPress={() => {

                    }}>
                    <Image style={[styles.showImage,{marginRight:5}]} source={ele}/>
                    <TouchableHighlight
                        style={styles.remove}
                        underlayColor='#c8c7cc'
                        onPress={() => this._removeImg(index)}>
                        <Text style={{fontSize:10,color:'#fff'}}>X</Text>
                    </TouchableHighlight>
                </TouchableOpacity>
            );
        });
    }

    _renderDetailImgs(){
        return this.state.detaiImgs.map((ele, index) => {
            return(
                <TouchableOpacity
                    key = {'detail'+index}
                    onPress={() => {

                    }}>
                    <Image style={[styles.showImage,{marginTop:index === 0?0:10}]} source={ele}/>
                    <TouchableHighlight
                        style={styles.remove}
                        underlayColor='#c8c7cc'
                        onPress={() => this._removeDetailImg(index)}>
                        <Text style={{fontSize:10,color:'#fff'}}>X</Text>
                    </TouchableHighlight>
                </TouchableOpacity>
            );
        });
    }

    _removeDetailImg(index){
        this.state.detaiImgs.splice(index, 1);
        this.setState({
            detaiImgs:this.state.detaiImgs
        })
    }

    _removeImg(index) {
        this.state.productImgs.splice(index, 1)
        this.setState({
            productImgs:this.state.productImgs
        })
    }

    _showImage(index){
        this.setState({
            showImage:true,
            ShowIndex:index
        });
    }

    _matchHttpImgs(url){
        return /^(http)/g.test(url);
    }


    submit(){
        if(!_lat){
            Toast.info('未标注地址', 1);
            return;
        }
        this.props.form.validateFields((error, value) => {
            if(!error){
                this.setState({
                    animating:true
                });
                let focusimg = [],imgUrl = {},acontent_img=[];
                if(this._matchHttpImgs(this.state.logoImage.uri)){
                    //imgUrl.imgUrl = this.state.logoImage.uri.replace('http://www.weiweigo.com','');
                    imgUrl.imgUrl = ' ';
                }else{
                    this._uploadImg(this.state.logoImage,imgUrl,4);
                }

                for(let ele of this.state.productImgs){
                    if(this._matchHttpImgs(ele.uri)){
                        focusimg.push(ele.uri.replace('http://www.weiweigo.com',''))
                    }else{
                        this._uploadImg(ele,focusimg,3);
                    }
                }
                for(let ele of this.state.detaiImgs){
                    if(this._matchHttpImgs(ele.uri)){
                        acontent_img.push(ele.uri.replace('http://www.weiweigo.com',''))
                    }else{
                        this._uploadImg(ele,acontent_img,6);
                    }

                }
                this._timer = setInterval(function(){
                    if(imgUrl.imgUrl && focusimg.length === this.state.productImgs.length && this.state.detaiImgs.length === acontent_img.length){
                        clearInterval(this._timer);
                        if(this.props.id && this.props.id != 0){
                            value.id = this.props.id;
                        }
                        let _body = {
                            ...value,
                            ClassID:value.ClassID[0],
                            imgUrl:imgUrl.imgUrl,
                            lat:_lat,
                            lon:_lng,
                            focusimg:JSON.stringify(focusimg.map(ele=>{
                                return {
                                    src:ele
                                }
                            })),
                            acontent_img:JSON.stringify(acontent_img.map(ele=>{
                                return {
                                    src:ele
                                }
                            }))
                        };

                        let formData = new FormData();

                        Object.keys(_body).map(ele=>{
                            formData.append(ele, _body[ele]);
                        });
                        XFetch(`http://www.weiweigo.com/app/server.aspx?method=edit`,{
                            method:'POST',
                            headers:{
                                "Content-Type": "multipart/form-data"
                            },
                            body:formData
                        }).then(data=>{
                            if(data){
                                console.log(data);
                                Toast.success('修改成功', 1);
                                this.setState({
                                    animating:false
                                })
                                AsyncStorage.setItem('serveid',String(data),()=>{
                                    this.props.navigator.pop();
                                });
                            }
                        });
                    }
                }.bind(this),1000);

            }
        });
    }

    _onMap(){
        this.props.navigator.push({
            name:'MapSelect',
            component:MapSelect,
            params:{
                getLocation:this._getLocation.bind(this),
                lat:_lat,
                lng:_lng
            }
        })
    }

    _getLocation(lat,lng){
        //console.log(lat,lng);
        _lat = lat;
        _lng = lng;
    }

    componentWillUnmount(){
        _lat = null;
        _lng = null;
    }

    render() {
        const { getFieldProps } = this.props.form;
        return (
            <View style={styles.container}>
                <NavTitle
                    title='修改我的店铺'
                    leftButton = {true}
                    leftText = {'返回'}
                    leftImg = {require('../imgs/left.png')}
                    leftHander = {()=>{this.props.navigator.pop()}}
                    headColor = '#fbdc3a'
                />
                <ScrollView
                    showsVerticalScrollIndicator={false}
                >
                <View style={styles.content}>
                    <View style={styles.logoHead}>
                        {
                            this.state.logoImage?<Image source={this.state.logoImage} style={styles.logoImg}/>:null
                        }
                        <TouchableOpacity style={styles.logoBtn} onPress={this._selectLogo.bind(this)}>
                            <Text style={styles.logoTxt}>选择头像</Text>
                        </TouchableOpacity>
                        <Text style={{marginLeft:10}}>100*100</Text>
                    </View>
                    <View style={[styles.proHead]}>
                        <TouchableOpacity style={styles.proBtn} onPress={this._selectProductImgs.bind(this)}>
                            <Image source={this.state.productImgs[0]} style={{width:Dimensions.get('window').width - 10,height:80}}></Image>
                        </TouchableOpacity>
                    </View>

                    <View style={styles.inputContent}>
                        <InputItem
                            clear
                            placeholder="服务名称"
                            {...getFieldProps('Name',{
                                rules: [{required: true}],
                            })}
                            labelNumber={5}
                            maxLength = {20}
                        >服务名称</InputItem>
                        <Picker
                            data={this.state.classifys}
                            title="分类选择"
                            {...getFieldProps('ClassID',{
                                rules: [{required: true}],
                            })}
                            cols={1}
                        >
                            <List.Item arrow="horizontal">分类</List.Item>
                        </Picker>

                        <InputItem
                            clear
                            placeholder="联系电话"
                            {...getFieldProps('tel',{
                                rules: [{required: true}],
                            })}
                            labelNumber={5}
                            maxLength = {10}
                        >联系电话</InputItem>

                        <InputItem
                            clear
                            placeholder="服务地址"
                            {...getFieldProps('addressDetail',{
                                rules: [{required: true}],
                            })}
                            labelNumber={5}
                            maxLength = {50}
                        >服务地址</InputItem>

                        <List className="my-list">
                            <Item extra={<Text style={{color:'#666'}}>选择地址</Text>} onClick={this._onMap.bind(this)}>地图标注</Item>
                        </List>

                        <List renderHeader={() => '服务介绍'}>
                            <TextareaItem
                                rows={3}
                                {...getFieldProps('summary',{
                                    rules: [{required: true}],
                                })}
                                placeholder="服务介绍"
                            />
                        </List>
                    </View>
                    <View style={{flex:1,backgroundColor:"#FFF",marginTop:10}}>
                    <ScrollView contentContainerStyle={[styles.proHead,styles.addBtn]} showsHorizontalScrollIndicator={false}>
                        {
                            this._renderDetailImgs()
                        }
                        <TouchableOpacity style={styles.detailBtn} onPress={this._selectDetailImgs.bind(this)}>
                            <Text style={[styles.proTxt,{fontSize:40}]}>+</Text>
                        </TouchableOpacity>
                    </ScrollView>
                    </View>
                    <List renderHeader={() => '服务内容'}>
                        <TextareaItem
                            rows={6}
                            {...getFieldProps('acontent',{
                                rules: [{required: true}],
                            })}
                            placeholder="服务内容"
                        />
                    </List>



                    {/*<View style={styles.head}>
                        <Image source={require('../imgs/eye.png')} style={styles.eye}></Image>
                        <Text style={styles.text}>预览内容</Text>
                    </View>

                    <View style={styles.btnInput}>
                        <TextInput
                            style={styles.telInput}
                            placeholder='请输入商家详情'
                            onChangeText={(text) => this.setState({username:text})}
                            underlineColorAndroid='transparent'
                            keyboardType = 'numeric'
                            multiline = {true}
                            autoFocus={true}
                        />
                    </View>*/}


                    <View style={{padding:10}}>
                        <TouchableHighlight
                            style={styles.loginBtn}
                            onPress={this.submit.bind(this)}
                        >
                            <Text style={styles.loginText}>确定</Text>
                        </TouchableHighlight>
                    </View>

                </View>
                </ScrollView>
                <ActivityIndicator
                    toast
                    text="加载中"
                    animating={this.state.animating}
                />
            </View>
        )
    }

}

const styles = StyleSheet.create({
    container: {
        backgroundColor: '#EEEEEF',
        flex: 1,
    },
    head:{
        flexDirection:'row',
        alignItems:'center',
        padding:10
    },
    eye:{
        width:25,
        height:20
    },
    text:{
        fontSize:14,
        color:'#333',
        marginLeft:5
    },
    itemStyle:{
        flexDirection:'row'
    },
    keys:{
        marginRight:10,
    },
    content:{
        padding:0,
    },
    telInput:{
        padding:5,
        paddingLeft:10,
        height:120,
        fontSize:16,
        flex:1
    },
    btnInput:{
        borderWidth:1/PixelRatio.get(),
        marginTop:20,
        borderRadius:4,
        borderColor:'#CCC',
        flexDirection:'row',
        backgroundColor:'#FFF',
        marginBottom:20
    },
    inputContent:{
        backgroundColor:'#FFF'
    },

    loginBtn:{
        padding:15,
        backgroundColor:'#FBDC3A',
        marginTop:20,
        borderRadius:3,
        justifyContent:'center',
        alignItems:'center'
    },
    logoHead:{
        flexDirection:'row',
        alignItems:'center',
        padding:5
    },
    logoBtn:{
        borderWidth:1/PixelRatio.get(),
        borderRadius:3,
        borderColor:'#CCC',
        backgroundColor:'#FFF',
        padding:4,
        paddingLeft:5,
        paddingRight:5
    },
    detailBtn:{
        width:80,
        height:80,
        borderWidth:1/PixelRatio.get(),
        borderRadius:3,
        borderColor:'#CCC',
        alignItems:'center',
        justifyContent:'center',
        marginTop:10
    },
    logoTxt:{
        fontSize:13
    },
    proHead:{
        flexDirection:'column',
        alignItems:'center',
    },
    addBtn:{
        padding:5,
        backgroundColor:"#FFF",
        justifyContent:'center',
        marginTop:10,
        marginBottom:10
    },
    proBtn:{
        alignItems:'center',
        justifyContent:'center'
    },
    proTxt:{
        fontSize:13,
        color:'#666'
    },
    loginText:{
        fontSize:16
    },
    logoImg:{
        width:80,
        height:80,
        marginRight:5
    },
    showImage:{
        width:80,
        height:80
    },
    remove:{
        position: 'absolute',
        top: 3,
        right: -3,
        width: 16,
        height: 16,
        borderRadius: 8,
        backgroundColor: '#000',
        alignItems:'center',
        justifyContent:'center'
    }
});

export default createForm()(EditMyService);
